


from flask import Blueprint, request, jsonify, g
import psycopg2.extras

from db_utils.postgresql_connection import PostgreSQLConnection

from db_utils.repositories.devices_table import DevicesTable
from db_utils.repositories.device_types_table import DeviceTypesTable
from db_utils.repositories.device_users_table import DeviceUsersTable
from db_utils.repositories.device_data_table import DeviceDataTable


# from db_utils.repositories.device_data_table import DeviceDataTable
# from db_utils.repositories.device_data_history_table import DeviceDataHistoryTable

import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

device_blueprint = Blueprint('device_blueprint', __name__)




#################################### device types table ##################################

# 创建设备类型
@device_blueprint.route('/create_device_type', methods=['POST'])
def create_device_type():
    
    device_type_name = request.form.get('device_type_name')
    description = request.form.get('description')

    if not all([device_type_name, description]):

        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        DeviceTypesTable(conn, cursor).create_device_type(device_type_name, description)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"device_type_id": 1}})
    

# update设备类型
@device_blueprint.route('/update_device_type', methods=['POST'])
def update_device_type():
    
    device_type_id = request.form.get('device_type_id')
    device_type_name = request.form.get('device_type_name')
    description = request.form.get('description')

    if not all([device_type_id, device_type_name, description]):
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):  

        DeviceTypesTable(conn, cursor).update_device_type(device_type_id, device_type_name, description)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "更新成功"})
    

# 获取所有设备类型
@device_blueprint.route('/get_all_device_types', methods=['GET'])
def get_all_device_types():
    
    with PostgreSQLConnection() as (conn, cursor):

        device_types = DeviceTypesTable(conn, cursor).get_all_device_types()

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_types})
    

# 根据设备类型ID获取设备类型信息
@device_blueprint.route('/get_device_type_by_id', methods=['GET'])
def get_device_type_by_id():
    
    device_type_id = request.args.get('device_type_id')
    
    with PostgreSQLConnection() as (conn, cursor):

        device_type_info = DeviceTypesTable(conn, cursor).get_device_type_by_id(device_type_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_type_info})
    
# 根据设备类型名称获取设备类型信息
@device_blueprint.route('/get_device_type_by_name', methods=['GET'])
def get_device_type_by_name():
    
    device_type_name = request.args.get('device_type_name')
    
    with PostgreSQLConnection() as (conn, cursor):

        device_type_info = DeviceTypesTable(conn, cursor).get_device_type_by_name(device_type_name)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_type_info})





########################################## devices table ################################
# 创建设备
@device_blueprint.route('/create_device', methods=['POST'])
def create_device():
    
    device_type_id = request.form.get('device_type_id')
    device_code = request.form.get('device_code')
    status = request.form.get('status')

    if not all([device_type_id, device_code, status]):

        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        DevicesTable(conn, cursor).create_device(device_type_id, device_code, status) # (True, 1)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"device_id": 1}})
    

# 解除设备与用户的绑定关系
@device_blueprint.route('/delete_device_user_relation', methods=['POST'])
def delete_device_user_relation():

    device_id = request.form.get('device_id')

    if not device_id :
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    # 查询设备是否是当前用户的
    with PostgreSQLConnection() as (conn, cursor):

        device_user_relation = DeviceUsersTable(conn, cursor).get_device_user_relation(device_id, g.user_id)

        if not device_user_relation:
    
            return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "没有权限删除该设备", "resultBody": None})
        
        DeviceUsersTable(conn, cursor).delete_device_user_relation(device_id, g.user_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "解除绑定成功"})
        

# 根据设备ID获取设备信息
@device_blueprint.route('/get_device_by_id', methods=['GET'])
def get_device_by_id():

    device_id = request.args.get('device_id')
    
    with PostgreSQLConnection() as (conn, cursor):

        device_info = DevicesTable(conn, cursor).get_device_by_id(device_id)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_info})
    
# 根据设备编码获取设备信息
@device_blueprint.route('/get_device_by_code', methods=['GET'])
def get_device_by_code():
    
    device_code = request.args.get('device_code')
    
    with PostgreSQLConnection() as (conn, cursor):

        device_info = DevicesTable(conn, cursor).get_device_by_code(device_code)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_info})
    

# 修改设备信息
@device_blueprint.route('/update_device_info', methods=['POST'])
def update_device_info():
    
    device_id = request.form.get('device_id')
    device_type_id = request.form.get('device_type_id')
    device_code = request.form.get('device_code')
    status = request.form.get('status')

    if not all([device_id, device_type_id, device_code, status]):
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        DevicesTable(conn, cursor).update_device(device_id, device_type_id, device_code, status)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "更新成功"})

# 查询所有设备 高权限用户
@device_blueprint.route('/get_all_devices', methods=['GET'])
def get_all_devices():
    
    device_type_id = request.args.get('device_type_id', type=int, default=None)
    device_code = request.args.get('device_code', default=None)
    status = request.args.get('status', default=None)
    limit = request.args.get('limit', default=10, type=int)
    offset = request.args.get('offset', default=0, type=int)

    with PostgreSQLConnection() as (conn, cursor):

        devices_table = DevicesTable(conn, cursor)
        devices = devices_table.get_all_devices(device_type_id, device_code, status, limit, offset)
        count = devices_table.count_all_devices(device_type_id, device_code, status)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": {"list": devices, "count": count}})
    
    



################################ device users table ##############################

# 绑定设备与用户
@device_blueprint.route('/bind_device_user', methods=['POST'])
def bind_device_user():
    
    device_id = request.form.get('device_id')
    user_id = request.form.get('user_id')


    if not device_id and not user_id:
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        device_user_table = DeviceUsersTable(conn, cursor)


        status, device_user_relation = device_user_table.get_device_user_relation(device_id, user_id)

        if status:

            if device_user_relation['relation_status'] == 'bind':
    
                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "设备已绑定"})
            
            else:
    
                status = device_user_table.update_device_user_relation(device_id, user_id, 'bind')

                if not status:
    
                    return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "绑定失败", "resultBody": None})

                return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "绑定成功"})
        
        else:

            status, error_msg = device_user_table.create_device_user_relation(device_id, user_id)

            if not status:
        
                return jsonify({"status": -1, "errorCode": 1001, "errorMsg": error_msg, "resultBody": None})

            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "绑定成功"})
    

# 解除设备与用户的绑定关系
@device_blueprint.route('/unbind_device_user', methods=['POST'])
def get_device_user_relation():
    
    device_id = request.form.get('device_id')
    user_id = request.form.get('user_id')

    if not device_id and not user_id :
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        status, error_msg = DeviceUsersTable(conn, cursor).update_device_user_relation(device_id, user_id, 'unbind')

        if not status:

            return jsonify({"status": -1, "errorCode": 1001, "errorMsg": error_msg, "resultBody": None})
                                                                   
        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "解除绑定成功"})
    

# 获取用户绑定的设备列表
@device_blueprint.route('/get_user_device_relations')
def get_user_device_relations():

    user_id = request.args.get('user_id')

    if not user_id:

        user_id = g.user_id
    
    with PostgreSQLConnection() as (conn, cursor):

        device_user_relations = DeviceUsersTable(conn, cursor).get_user_device_relations(user_id) #（True, [{'device_id': 1, 'device_code': '123456', 'device_type_id': 1,'status': 'active', 'user_id': 1, 'user_name': 'admin', 'user_email': 'admin@admin.com','relation_status': 'bind'}]）

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_user_relations[1]})


# 获取设备 - 用户关联关系列表
@device_blueprint.route('/get_device_user_relations')
def get_device_user_relations():
    
    device_id = request.args.get('device_id')

    if not device_id :
        
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        device_user_relations = DeviceUsersTable(conn, cursor).get_device_user_relations(device_id) #（True, [{'device_id': 1, 'device_code': '123456', 'device_type_id': 1,'status': 'active', 'user_id': 1, 'user_name': 'admin', 'user_email': 'admin@admin.com','relation_status': 'bind'}]）

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_user_relations[1]})

#################################### device data table #################################



# 创建设备数据
@device_blueprint.route('/create_device_data', methods=['POST'])
def create_device_data():
    
    device_id = request.form.get('device_id')
    data_type = request.form.get('data_type')
    data_json = request.form.get('data_json')
    data_direction = request.form.get('data_direction')

    if not all([device_id, data_type, data_json, data_direction]):
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        DeviceDataTable(conn, cursor).create_device_data(device_id, data_type, data_json, data_direction)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "创建成功"})
    

# 删除设备数据
@device_blueprint.route('/delete_device_data', methods=['POST'])
def delete_device_data():
    
    device_id_list = request.form.getlist('device_id_list[]')

    if not device_id_list:
    
        return jsonify({"status": -1, "errorCode": 1001, "errorMsg": "缺少参数", "resultBody": None})

    with PostgreSQLConnection() as (conn, cursor):

        DeviceDataTable(conn, cursor).delete_device_data(device_id_list)

        return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": "删除成功"})

# 数据查询
@device_blueprint.route('/get_device_data', methods=['GET'])
def get_device_data(): # def get_device_data(self, device_id=None, data_direction=None, date_start=None, date_end=None, limit=20, offset=0):

    device_id = request.args.get('device_id')
    data_direction = request.args.get('data_direction')
    date_start = request.args.get('date_start')
    date_end = request.args.get('date_end')
    limit = request.args.get('limit', default=20, type=int)
    offset = request.args.get('offset', default=0, type=int)

    with PostgreSQLConnection() as (conn, cursor):

        device_data_result = DeviceDataTable(conn, cursor).get_device_data(device_id, data_direction, date_start, date_end, limit, offset)

        if device_data_result[0]:
    
            return jsonify({"status": 1, "errorCode": None, "errorMsg": None, "resultBody": device_data_result[1]})
        
        else:

            return jsonify({"status": -1, "errorCode": 1001, "errorMsg": f"查询失败: {device_data_result[1]}", "resultBody": None})